import pymysql.cursors


# 封装后后续接口测试用例需要操作数据库时，就可以引入该模块，实例化对象调用该模块下的方法。

class Operation_mysql(object):
    def __init__(self):
        # 建立连接
        db_config = {
            "host": "119.29.78.234",
            "port": 3306,
            "user": "root",
            "password": "dhcc@2020",
            "db": "test123"
        }
        self.connection = pymysql.connect(**db_config)
        # 创建游标
        self.cursor = self.connection.cursor()

    def execute_sql(self, sql):
        try:
            self.cursor.execute(sql)
            self.connection.commit()
        except Exception as e:  # 执行异常回滚
            db.rollback()

    def get_data(self):
        data = self.cursor.fetchone()
        # data = self.cursor.fetchall() # 查询所有数据
        return data

    def close_mysql(self):
        # 关闭游标
        self.cursor.close()
        # 关闭数据库连接
        self.connection.close()
